#include "NameManager.h"

#include <iostream>
#include <fstream>
#include <cassert>
#include <algorithm>

using namespace std;

NameManager::NameManager() : m_loaded(false)
{
	bool isLoaded = LoadFromFile("names.txt","surnames.txt", "teams.txt");
	assert(isLoaded);
}

bool NameManager::LoadFromFile(const string& i_Names , const string& i_Surnames, const std::string& i_teams)
{
	ifstream infile(i_Names.c_str());
	if (infile.fail()) 
		return false;
	
	string s;
    
	while (getline(infile, s))
	{
    	m_names.push_back(s);
	}

	ifstream infile2(i_Surnames.c_str());
	if (infile2.fail()) 
		return false;

	while (getline(infile2, s))
	{
    	m_surnames.push_back(s);
	}

	ifstream infile3(i_teams.c_str());
	if (infile3.fail()) 
		return false;

	while (getline(infile3, s))
	{
    	m_teams.push_back(s);
	}

	m_loaded = true;

	return true;
}

string NameManager::GetAPlayerName() const
{
	if (!IsLoaded()) 
		return "";

	return m_surnames[rand()%(m_surnames.size())] + " "+ m_names[rand()%(m_names.size())];
}

string NameManager::GetATeamName() const
{
	if (!IsLoaded()) 
		return "";
	
	int selected = rand()%(m_teams.size());
	while (
		std::find( m_usedNames.begin(), m_usedNames.end(), selected ) != m_usedNames.end()
		)
	{
		selected = rand()%(m_teams.size());
	}
	
	m_usedNames.push_back (selected);
	return m_teams[selected];
}

void NameManager::SetTeamNameUsed(const std::string& i_name) const
{
	
	strContainer::const_iterator it = std::find( m_teams.begin(), m_teams.end(), i_name);

	if(it == m_teams.end())
		return;

	size_t index = it - m_teams.begin();
	
	m_usedNames.push_back(index);
}

void NameManager::Clear()
{
	m_usedNames.clear();
}
